define(function(require, exports){
  'use strict';

  var $ = require('seajs/jquery.min');
  var SimpleMap = require('seajs/plugs/simpleMap');
  var _const = require('seajs/fn/fnConst');
  var fnModal = require('seajs/fn/fnModal');
  var fnUtils = require('seajs/fn/fnUtils');
  var FnTemporaryGroup = require('seajs/fn/fnTemporaryGroup');
  var FnBoardcast = require('seajs/fn/fnBoardcast');

  var getTemporaryGroupMemberIds = function(data, success, error){
    $.ajax({  
      type:'GET',
      url:'http://' 
        + _const.HTTP.CONFIG.HOST + ':' 
        + _const.HTTP.CONFIG.PORT + '/' 
        + _const.HTTP.CONFIG.PATH + 'group/getTemporaryGroupMembersStatus.do?'
        + 'userid=' + data['userid'] + '&'
        + 'userType=' + data['userType'] + '&'
        + 'companyid=' + data['companyid'] + '&'
        + 'timestamp=' + data['timestamp'] + '&'
        + 'key=' + data['key'] + '&'
        + 'groupId=' + data['groupId'] + '&'
        + 'token=' + data['token'],
      dataType:'json',
      success: function(rlt){
        console.log('========== getTemporaryGroupMembers() ==========');
        console.log('rlt:', rlt);
        if(rlt.status === _const.HTTP.RES_STATUS.SUCCESS){
          if(rlt.error.code === _const.HTTP.RES_STATUS.ERROR_CODE.FAIL){
            alert(rlt.error.message);
          }else{
            success(rlt);
          }
        }
      },
      error:function(e){
        console.log('========== getTemporaryGroupMembers() ==========');
        console.log('e:', e);
      }
    });
  }

  var getTemporaryGroupMembers4Broadcast = function(data, success, error){
    $.ajax({  
      type:'GET',
      url:'http://' 
        + _const.HTTP.CONFIG.HOST + ':' 
        + _const.HTTP.CONFIG.PORT + '/' 
        + _const.HTTP.CONFIG.PATH + 'group/getTemporaryGroupMembers4Broadcast.do?'
        + 'userid=' + data['userid'] + '&'
        + 'userType=' + data['userType'] + '&'
        + 'companyid=' + data['companyid'] + '&'
        + 'timestamp=' + data['timestamp'] + '&'
        + 'key=' + data['key'] + '&'
        + 'groupId=' + data['groupId'] + '&'
        + 'token=' + data['token'],
      dataType:'json',
      success: function(rlt){
        console.log('========== getTemporaryGroupMembers4Broadcast() ==========');
        console.log('rlt:', rlt);
        if(rlt.status === _const.HTTP.RES_STATUS.SUCCESS){
          if(rlt.error.code === _const.HTTP.RES_STATUS.ERROR_CODE.FAIL){
            alert(rlt.error.message);
          }else{
            success(rlt);
          }
        }
      },
      error:function(e){
        console.log('========== getTemporaryGroupMembers4Broadcast() ==========');
        console.log('e:', e);
      }
    });
  }

  // <li class="btn-group" id="task_575">
  //    <div class="task-fill-out"></div>
  //    <div class="task-content">
  //        <div>广播中</div>
  //        <div>
  //             <div class="task-talking-status"></div>
  //             <div class="task-end-btn">解散</div>
  //        </div>
  //    </div>
  // </li>
      //结束临时对讲

  var getTaskDom = function(container, task,map,groupName,boardName){

    var taskLi = document.createElement('li');
    taskLi.className = 'btn-group';
    taskLi.id = 'task_' + task.id;
    if(task.eventType === _const.TASK_TYPE.BOARDCAST 
      || task.eventType === _const.TASK_TYPE.TEMPORARY_GROUP){
      var fillOut = document.createElement('div');
      fillOut.onclick = function(){
        switch(task.eventType){
          case _const.TASK_TYPE.BOARDCAST:
             if(container.boardcast.isCreated === false){
              container.boardcast.initBCDialog();
              container.boardcast.initSelectDialog(container.boardcastData);
              container.boardcast.initBoardcastDialog();
              container.boardcast.openBCDialog();
              container.boardcast.isCreated = true;
            }else{
              container.boardcast.openBCDialog();
            }
            break;
          case _const.TASK_TYPE.TEMPORARY_GROUP:
              if(container.temporaryGroup.isCreated === false){
                container.temporaryGroup.initSelectDialog(container.ws.slidebar.groupMap.map, container.temporaryGroupData);
                container.temporaryGroup.initTGDialog(container.temporaryGroupData);
              }
              container.temporaryGroup.showTGDialog(container.temporaryGroupData);
              container.temporaryGroup.isCreated = true;
            break;
          default:
        };
      };
      fillOut.className = 'task-fill-out';
      taskLi.appendChild(fillOut);

      // 任务信息
      var content = document.createElement('div');
      content.className = 'task-content';
      var contentTopic = document.createElement('div');
      contentTopic.innerHTML = task.topic;
      var taskBtns = document.createElement('div');
      var taskBtnStatus = document.createElement('div');
      taskBtnStatus.className = 'task-talking-status';
      taskBtns.appendChild(taskBtnStatus);
      var taskEnd = document.createElement('div');
      taskEnd.className = 'task-end-btn';
      switch(task.eventType){
        case _const.TASK_TYPE.BOARDCAST:
          taskEnd.innerHTML = '结束';
          taskEnd.onclick = function(){
            $('#confirmInfo').html('确定结束当前广播?'); 
            $('#confirm_btn').off('click').on('click', function(){
              container.ws.boardCastHangUp(task.cid, task.sid, task.id);
            });
            $('#confirm_modal').modal('show');
          }
          break;
        case _const.TASK_TYPE.TEMPORARY_GROUP:
          taskEnd.innerHTML = '解散';
          taskEnd.onclick = function(){

            $('#confirmInfo').html('确定解散当前临时组?'); 
            $('#confirm_btn').off('click').on('click', function(){
              //就是这里
              console.log(map);
              container.ws.temporaryTalkHangUp(task.cid, task.sid, task.id);
              container.ws.overTalkSite(map);

            });
            $('#confirm_modal').modal('show');
          }
          default:
      };
      taskBtns.appendChild(taskEnd);
      content.appendChild(contentTopic);
      content.appendChild(taskBtns);

      taskLi.appendChild(content);
    }else{
      // <li class="btn-group" id="task_575">
      //   <div class="task-content">
      //       <div>小林小玲小林小玲</div>
      //       <div>
      //           <div class="task-single-talk-status">单呼中</div>
      //           <div class="task-end-btn">解散</div>
      //      </div>
      //  </div>
      // </li>
      var content = document.createElement('div');
      content.className = 'task-content';
      var contentTopic = document.createElement('div');
      contentTopic.innerHTML = 'XXXX';
      var taskBtns = document.createElement('div');
      var taskBtnStatus = document.createElement('div');
      taskBtnStatus.className = 'task-single-talk-status';
      taskBtnStatus.innerHTML = '单呼中';
      taskBtns.appendChild(taskBtnStatus);
      var taskEnd = document.createElement('div');
      taskEnd.className = 'task-end-btn';
     
      taskEnd.innerHTML = '挂断';
      taskEnd.onclick = function(){
        $('#confirmInfo').html('确定挂断当前单呼?'); 
        $('#confirm_btn').off('click').on('click', function(){
          container.ws.singleCallHangUp(task.cid, task.sid, task.id);
        });
        $('#confirm_modal').modal('show');
      }
      taskBtns.appendChild(taskEnd);
      content.appendChild(contentTopic);
      content.appendChild(taskBtns);

      taskLi.appendChild(content);
    }
    

    return taskLi;
  }

 /**
  * task {
  *	 event: 会议, 通话, 来电
  * }
  */
  var Tasks = function(ws){
    this.ws = ws;
  	this.taskMap = new SimpleMap();
    this.currentId = undefined;

    this.temporaryGroup = undefined; 
    this.temporaryGroupData = undefined;

    this.boardcast = undefined;
    this.boardcastData = undefined;

    this.singleCalledUid = undefined;

    this.init();
  }

  Tasks.prototype.init = function(){
    this.taskMap = new SimpleMap();
    this.temporaryGroup = new FnTemporaryGroup();
    this.temporaryGroupData = new SimpleMap(); 
    this.temporaryGroup.setWs(this.ws);
    this.boardcast = new FnBoardcast();
    this.boardcastData = new SimpleMap();
    this.boardcast.setWs(this.ws);
  }

  Tasks.prototype.setCurrentId = function(currentId){
    this.currentId = currentId;
  }

  Tasks.prototype.getCurrentId = function(){
    return this.currentId;
  }

  Tasks.prototype.remove = function(id){
    if(id){
      var task = this.taskMap.get(id);
      this.temporaryGroup.enabledOpenBtn();
      this.boardcast.enabledOpenBtn();
      this.ws.slidebar.enableRAll();
      if(task.eventType === _const.TASK_TYPE.TEMPORARY_GROUP){
        this.temporaryGroup.clearTGDialog();
        this.temporaryGroup.isCreated = false;
        $('#temporaryGroup').modal('hide');     
        $('#confirm_modal').modal('hide');
      }else if(task.eventType === _const.TASK_TYPE.BOARDCAST){
        $('#boardcast').modal('hide'); 
        $('#confirm_modal').modal('hide');
        this.boardcast.isCreated = false;
      }else if(task.eventType === _const.TASK_TYPE.SINGLE_CALL){
        $('#confirm_modal').modal('hide');
      }else{

      }
      this.ws.slidebar.setTalkStatus(1,
          this.ws.slidebar.groupMap.get(this.ws.slidebar.joinedGroup).groupName, 6, 2);
      this.taskMap.remove(id);
      $('#task_' + id).remove();
      this.currentId = undefined;
    }
  }

  Tasks.prototype.put = function(task){
    var self = this;
    if(task && !self.taskMap.get(task.id)){
      self.taskMap.put(task.id, task);
      if(self.currentId === undefined){
        self.currentId = task.id;
      }
      self.ws.slidebar.disableRAll();

      self.temporaryGroup.disabledOpenBtn();
      self.boardcast.disabledOpenBtn();
      if(task.eventType === _const.TASK_TYPE.TEMPORARY_GROUP){
        if(self.temporaryGroup.tgMemberMap.size() === 0){
          var data = fnUtils.getToken({
            'userid': parseInt(self.ws.uid),
            'userType': _const.DEVICE.DISPATCHER,
            'companyid': parseInt(self.ws.cmpid),
            'timestamp': fnUtils.getUnixTime() + '',
            'key': self.ws.key,
            'groupId': task.id
          }, _const.FN_KEY);
          getTemporaryGroupMemberIds(data, function(rlt){
            for(var i = 0; i < rlt.body.length; i++){
              if(self.ws.slidebar.memberMap.get(rlt.body[i]['uid']) && rlt.body[i]['status'] === 1){
                self.temporaryGroupData.put(rlt.body[i]['uid'], self.ws.slidebar.memberMap.get(rlt.body[i]['uid']));
              }
            }
          });
          self.ws.slidebar.setTalkStatus(2, "临时对讲中");
        }
      }else if(task.eventType === _const.TASK_TYPE.BOARDCAST){
        if(self.boardcast.selectedMap.size() === 0){
          var data = fnUtils.getToken({
            'userid': parseInt(self.ws.uid),
            'userType': _const.DEVICE.DISPATCHER,
            'companyid': parseInt(self.ws.cmpid),
            'timestamp': fnUtils.getUnixTime() + '',
            'key': self.ws.key,
            'groupId': task.id
          }, _const.FN_KEY);
          getTemporaryGroupMembers4Broadcast(data, function(rlt){
            for(var i = 0; i < rlt.body.length; i++){
              self.boardcastData.put(rlt.body[i]['groupId'], self.ws.slidebar.groupMap.get(rlt.body[i]['groupId']));
            }
          });
          self.ws.slidebar.setTalkStatus(2, "广播中");
        }

        self.boardcast.initBoardcastDialog();
        self.boardcast.hideAlert();

      }else if(task.eventType === _const.TASK_TYPE.SINGLE_CALL){
         var data = fnUtils.getToken({
            'userid': parseInt(self.ws.uid),
            'userType': _const.DEVICE.DISPATCHER,
            'companyid': parseInt(self.ws.cmpid),
            'timestamp': fnUtils.getUnixTime() + '',
            'key': self.ws.key,
            'groupId': task.id
          }, _const.FN_KEY);

          getTemporaryGroupMemberIds(data, function(rlt){
            if(rlt.body.length > 0){
              self.singleCalledUid = rlt.body[0]['uid'];
              $('.task-content > div:first').html(self.ws.slidebar.memberMap.get(rlt.body[0]['uid']).memberName);
            }
          }, function(e){
            console.log(e);
          });
         self.ws.slidebar.setTalkStatus(2, "单呼中");
      }
      $('#taskUl').append(getTaskDom(self, task, self.temporaryGroup.map.map,self.temporaryGroup.groupName,self.boardcast.groupName));
    }
  }

  Tasks.prototype.join = function(id, uid){
    if(id && uid){
      $('#task_' + id + '_drop_menu_li_' + uid).insertBefore($('#task_' + id + '_drop_menu_ul li:first'));
      $('#task_' + id + '_drop_menu_li_span_i_' + uid)
        .removeClass('text-grey')
        .removeClass('text-green')
        .addClass('text-blue');
    }
  }

  Tasks.prototype.leave = function(id, uid){
    if(id && uid){
      $('#task_' + id + '_drop_menu_li_' + uid).insertBefore($('#task_' + id + '_drop_menu_ul li:last'));
      //下线
      var member = this.ws.slidebar.memberMap.get(uid);
      if(member['status'] == _const.IS_ON_LINE.OFF_LINE){
        $('#task_' + id + '_drop_menu_li_span_i_' + uid)
          .removeClass('text-blue')
          .removeClass('text-green')
          .addClass('text-grey');
      }else{
        $('#task_' + id + '_drop_menu_li_span_i_' + uid)
          .removeClass('text-blue')
          .removeClass('text-grey')
          .addClass('text-green');
      }
    }
  }

  return Tasks;
});